package com.sparrow.common.schedule.condition;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 带条件的任务调度器
 */
public class ConditionalScheduler {
    private static Logger logger = LoggerFactory.getLogger(ConditionalScheduler.class);

    private final ScheduledExecutorService scheduler;
    private final List<Condition> conditions;
    private final Runnable delayTask;
    private final int delay;
    private final TimeUnit timeUnit;
    private int attempt = 0;
    private int maxAttempt = 0;
    private final Runnable callback;
    private volatile boolean cancelled = false;

    public ConditionalScheduler(ScheduledExecutorService scheduler, List<Condition> conditions, Runnable delayTask, int delay, TimeUnit timeUnit, int maxAttempt, Runnable callback) {
        this.scheduler = scheduler;
        this.conditions = conditions;
        this.delayTask = delayTask;
        this.delay = delay;
        this.timeUnit = timeUnit;
        this.maxAttempt = maxAttempt;
        this.callback = callback;
    }

    public void cancel() {
        this.cancelled = true;
    }

    public void start() {
        scheduler.schedule(this::checkConditions, 0, TimeUnit.MILLISECONDS);
    }

    private void checkConditions() {
        if (cancelled) {
            logger.info("任务已被取消，停止调度");
            return;
        }
        boolean allMet = isAllConditionMet();
        if (allMet) {
            callback.run();
        } else if (attempt++ < maxAttempt){
            delayTask.run();
            scheduler.schedule(this::checkConditions, delay, timeUnit);
        } else {
            logger.info("尝试第 {}/{} 次，条件仍未满足，放弃执行", attempt, maxAttempt);
        }
    }

    public boolean isAllConditionMet() {
        return conditions.stream().allMatch(Condition::isMet);
    }
}

